package com.useeinfo.oa.open.api.inspection;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.lang.StringUtils;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Position;
import com.useeinfo.oa.modules.inspection.biz.FacilityInspectionSnapBiz;
import com.useeinfo.oa.modules.inspection.biz.InsAuditOrderBiz;
import com.useeinfo.oa.modules.inspection.biz.InspectionFocusBiz;
import com.useeinfo.oa.modules.inspection.biz.InspectionOrderBiz;
import com.useeinfo.oa.modules.inspection.entity.InsAuditOrder;
import com.useeinfo.oa.modules.inspection.entity.InspectionFocus;
import com.useeinfo.oa.modules.inspection.entity.InspectionOrder;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/inspectionDashboardReport")
public class InspectionDashboardReportAPI {
    @Autowired
    private FacilityInspectionSnapBiz facilityInspectionSnapBiz;
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private InspectionOrderBiz inspectionOrderBiz;
    @Autowired
    private InspectionFocusBiz inspectionFocusBiz;
    @Autowired
    private InsAuditOrderBiz insAuditOrderBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;

    /**
     * 作业人员(专业)工作完成情况统计
     * type:day/month 默认day
     */
    @RequestMapping(value = "/completePercent")
    public ResultDto completePercent(@RequestParam(value = "type", required = false) String type,
                                     @RequestParam(value = "enterpriseId", required = false) String enterpriseId){
        JSONObject data = new JSONObject();
        JSONArray rows = new JSONArray();
        if(enterpriseId==null){
            data.put("rows",rows);
            return ResultUtil.success(data);
        }
        //获取下级企业ids（包括自己）
        String ids = enterpriseBiz.childrenIds(enterpriseId);
        Date nowTime = new Date();
        String startDate = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getBeginOfDay(nowTime));
        String endDate = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getEndOfDay(nowTime));
        if("month".equals(type)){
            startDate = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getBeginOfDay(DateTimeUtils.getFirstDateOfMonth(nowTime)));
            endDate = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getEndOfDay(DateTimeUtils.getLastDateOfMonth(nowTime)));
        }
        rows = facilityInspectionSnapBiz.completePercent(ids,startDate,endDate);
        data.put("rows",rows);
        return ResultUtil.success(data);
    }

    /**
     * 正在维修中的设备
     */
    @RequestMapping(value = "/inspectionFacilityCount")
    public JSONObject inspectionFacilityCount(@RequestParam(value = "enterpriseId", required = false) String enterpriseId){
        JSONObject jsonObject = new JSONObject();
        if(enterpriseId==null){
            return jsonObject;
        }
        //获取下级企业ids（包括自己）
        String ids = enterpriseBiz.childrenIds(enterpriseId);
        JSONArray rows = inspectionOrderBiz.inspectionFacilityCount(ids);
        jsonObject.put("rows",rows);
        return jsonObject;
    }

    /**
     *
     */
    @RequestMapping(value = "/getOrderList")
    public JSONObject getOrderList(@RequestParam(value = "userId", required = false) String userId,
                                  @RequestParam(value = "pageIndex", required = false) String pageIndexParam,
                                  @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                  @RequestParam(value = "enterpriseId", required = false) String enterpriseId,
                                  @RequestParam(value = "type", required = false) String type){
        JSONObject data = new JSONObject();
        data.put("records",0);
        JSONArray rows = new JSONArray();
        data.put("rows",rows);
        if(StringUtils.isBlank(type)){
            return data;
        }
        SystemUser user = systemUserBiz.findModel(StringConverters.ToLong(userId));
        Enterprise enterprise = enterpriseBiz.findModel(StringConverters.ToLong(enterpriseId));
        if(user==null||enterprise==null){
            return data;
        }
        //查关注的工单
        if("focus".equals(type)){
            QueryParam queryParamF = new QueryParam(pageIndexParam,pageSizeParam);
            queryParamF.getSqlMap().put("systemUserId",userId);
            queryParamF.getSqlMap().put("enterpriseId",enterpriseId);
            List<InspectionFocus> inspectionFocusList = inspectionFocusBiz.findList(queryParamF);
            if(CollectionUtils.isNotEmpty(inspectionFocusList)){
                for(InspectionFocus inspectionFocus : inspectionFocusList){
                    if(inspectionFocus.getInspectionOrder()!=null){
                        InspectionOrder inspectionOrder = inspectionFocus.getInspectionOrder();
                        JSONObject json = inspectionOrder.toListJSONObject();
                        JSONArray tags = inspectionOrderBiz.getTags(inspectionOrder,user,null);
                        json.put("tags",tags);
                        rows.add(json);
                    }
                }
            }
            //查总数
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("systemUserId",userId);
            queryParam.getSqlMap().put("enterpriseId",enterpriseId);
            Long records = inspectionFocusBiz.totalRecord(queryParam.getSqlMap());
            if(records>0){
                data.put("records",records);
            }
        }
        //查发起的工单
        if("create".equals(type)){
            QueryParam queryParamC = new QueryParam(pageIndexParam,pageSizeParam);
            queryParamC.getSqlMap().put("systemUserId",userId);
            queryParamC.getSqlMap().put("enterpriseId",enterpriseId);
            List<InspectionOrder> inspectionOrderList = inspectionOrderBiz.findList(queryParamC);
            if(CollectionUtils.isNotEmpty(inspectionOrderList)){
                for(InspectionOrder inspectionOrder : inspectionOrderList){
                    JSONObject json = inspectionOrder.toListJSONObject();
                    JSONArray tags = inspectionOrderBiz.getTags(inspectionOrder,user,null);
                    json.put("tags",tags);
                    rows.add(json);
                }
            }
            //查总数
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("systemUserId",userId);
            queryParam.getSqlMap().put("enterpriseId",enterpriseId);
            Long records = inspectionOrderBiz.totalRecord(queryParam.getSqlMap());
            if(records>0){
                data.put("records",records);
            }
        }
        //查我接单的
        if("receive".equals(type)){
            QueryParam queryParamR = new QueryParam(pageIndexParam,pageSizeParam);
            queryParamR.getSqlMap().put("receiveUserId",userId);
            queryParamR.getSqlMap().put("enterpriseId",enterpriseId);
            List<InspectionOrder> inspectionOrderList = inspectionOrderBiz.findList(queryParamR);
            if(CollectionUtils.isNotEmpty(inspectionOrderList)){
                for(InspectionOrder inspectionOrder : inspectionOrderList){
                    JSONObject json = inspectionOrder.toListJSONObject();
                    JSONArray tags = inspectionOrderBiz.getTags(inspectionOrder,user,null);
                    json.put("tags",tags);
                    rows.add(json);
                }
            }
            //查总数
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("receiveUserId",userId);
            queryParam.getSqlMap().put("enterpriseId",enterpriseId);
            Long records = inspectionOrderBiz.totalRecord(queryParam.getSqlMap());
            if(records>0){
                data.put("records",records);
            }
        }
        //我审核的
        if("audit".equals(type)){
            Position position = user.getPosition(enterprise,user.getPositionSet());
            QueryParam queryParamA = new QueryParam(pageIndexParam,pageSizeParam);
            queryParamA.getSqlMap().put("auditUserId",userId);
            queryParamA.getSqlMap().put("enterpriseId",enterpriseId);
            // 获取审核中的工单
            queryParamA.getSqlMap().put("auditIn","auditIn");//包括取消审批，延期审批，正常审批
            if(position!=null){
                queryParamA.getSqlMap().put("auditPositionId",position.getId()+"");
            }
            List<InspectionOrder> inspectionOrderList = inspectionOrderBiz.findList(queryParamA);
            if(CollectionUtils.isNotEmpty(inspectionOrderList)){
                for(InspectionOrder inspectionOrder : inspectionOrderList){
                    JSONObject json = inspectionOrder.toListJSONObject();
                    JSONArray tags = inspectionOrderBiz.getTags(inspectionOrder,user,null);
                    json.put("tags",tags);
                    rows.add(json);
                }
            }
            //查总数
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("auditUserId",userId);
            queryParam.getSqlMap().put("enterpriseId",enterpriseId);
            if(position!=null){
                queryParam.getSqlMap().put("auditPositionId",position.getId()+"");
            }
            Long records = inspectionOrderBiz.totalRecord(queryParam.getSqlMap());
            if(records>0){
                data.put("records",records);
            }
        }
        //待接单的
        if("waitTaking".equals(type)){
            ResultDto resultDto = inspectionOrderBiz.list("0",pageIndexParam,pageSizeParam,user,enterprise,null,null);
            JSONObject jsonObject = JSONObject.parseObject(resultDto.getData().toString());
            rows = jsonObject.getJSONArray("rows");
            ResultDto resultDto1 = inspectionOrderBiz.list("0","-1","-1",user,enterprise,null,null);
            JSONObject jsonObject1 = JSONObject.parseObject(resultDto1.getData().toString());
            JSONArray array = jsonObject1.getJSONArray("rows");
            if(array.size()>0){
                data.put("records",array.size());
            }
        }
        data.put("rows",rows);
        return data;
    }
}
